package com.utils.http;




import java.io.File;
import java.io.FileInputStream;
import java.security.KeyStore;

import javax.net.ssl.SSLContext;

import org.apache.http.HttpEntity;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContexts;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import com.config.WeChatConfig;


public class HttpClientConnectionManager {
	
	
	
	/**
	 * 获取SSL验证的HttpClient
	 * @param httpClient
	 * @return
	 */
	public static HttpClient getSSLInstance(HttpClient httpClient){
		ClientConnectionManager ccm = httpClient.getConnectionManager();
		SchemeRegistry sr = ccm.getSchemeRegistry();
		sr.register(new Scheme("https", MySSLSocketFactory.getInstance(), 443));
		httpClient =  new DefaultHttpClient(ccm, httpClient.getParams());
		return httpClient;
	}
	
	/**
	 * 模拟浏览器post提交
	 * 
	 * @param url
	 * @return
	 */
	public static HttpPost getPostMethod(String url) {
		
		
		HttpPost pmethod = new HttpPost(url); // 设置响应头信息
		pmethod.addHeader("Connection", "keep-alive");
		//pmethod.addHeader("Connection", "close");
		pmethod.addHeader("Accept", "*/*");
		pmethod.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
		pmethod.addHeader("Host", "api.mch.weixin.qq.com");
		pmethod.addHeader("X-Requested-With", "XMLHttpRequest");
		pmethod.addHeader("Cache-Control", "max-age=0");
		pmethod.addHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0) ");
		return pmethod;
	}
	
	/**E:/Wechat_Cert/Wechat_CM/apiclient_cert.p12
	 * 模拟浏览器postSSL提交
	 * @param url    HTTPS地址
	 * @param xmlParam   请求参数
	 * @param sslFilePath  退款SSL安装地址
	 * @return
	 * POST请求
	 */
	public static String getPostMethodSSL(String url,String xmlParam) throws Exception{
		    KeyStore keyStore  = KeyStore.getInstance("PKCS12");
	        FileInputStream instream = new FileInputStream(new File("E:/Wechat_Cert/Wechat_CM/apiclient_cert.p12"));
	        String jsonStr="";
	        String mach_id = WeChatConfig.MACH_ID;
	        CloseableHttpResponse response=null;
	        try {
	            keyStore.load(instream, mach_id.toCharArray());
	        } finally {
	            instream.close();
	        }
	        SSLContext sslcontext = SSLContexts.custom()
	                .loadKeyMaterial(keyStore, mach_id.toCharArray())
	                .build();
	        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
	                sslcontext,
	                new String[] { "TLSv1" },
	                null,
	                SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
	        CloseableHttpClient httpclient = HttpClients.custom()
	                .setSSLSocketFactory(sslsf)
	                .build();
	        try {
	        	HttpPost httpost = new HttpPost(url); // 退款url
	            System.out.println("executing request" + httpost.getRequestLine());
	            try {
	    	        httpost.addHeader("Connection", "keep-alive");
	    	        httpost.addHeader("Accept", "*/*");
	    	        httpost.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
	    	        httpost.addHeader("Host", "api.mch.weixin.qq.com");
	    	        httpost.addHeader("X-Requested-With", "XMLHttpRequest");
	    	        httpost.addHeader("Cache-Control", "max-age=0");
	    	        httpost.addHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0) ");
	    	        httpost.setEntity(new StringEntity(xmlParam, "UTF-8"));
	    	        response = httpclient.execute(httpost);
	    	        HttpEntity entity = response.getEntity();
	    	        jsonStr = EntityUtils .toString(response.getEntity(), "UTF-8");
	    	        EntityUtils.consume(entity);
	            } finally {
	                response.close();
	            }
	        } finally {
	            httpclient.close();
	        }
		return jsonStr;
	}

	/**
	 * 模拟浏览器GET提交
	 * @param url
	 * @return
	 */
	public static HttpGet getGetMethod(String url) {
		HttpGet pmethod = new HttpGet(url);
		// 设置响应头信息
		pmethod.addHeader("Connection", "keep-alive");
		pmethod.addHeader("Cache-Control", "max-age=0");
		pmethod.addHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0) ");
		pmethod.addHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/;q=0.8");
		return pmethod;
	}
}
